﻿using JNPF.Basics.Models;
using JNPF.Data;
using JNPF.Utils;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 操作权限
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.11.07 
    /// </summary>
    internal class AuthorizeService : DataFactory, AuthorizeIService
    {
        /// <summary>
        /// 获取权限（菜单、按钮、列表）
        /// </summary>
        /// <param name="isAdmin">是否管理员</param>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<AuthorizeModel> GetAuthorize(bool isAdmin, string userId)
        {
            using (var db = this.Basic)
            {
                var moduleList = new List<AuthorizeModuleModel>();
                var buttonList = new List<AuthorizeModuleButtonModel>();
                var columnList = new List<AuthorizeModuleColumnModel>();
                var resourceList = new List<AuthorizeModuleResourceModel>();
                if (!isAdmin)
                {
                    var objectId = (await db.GetEntityAsync<UserEntity>(userId)).RoleId.Replace(",", "','");
                    moduleList = await db.GetListSqlAsync<AuthorizeModuleModel>(string.Format("SELECT * FROM Base_Module WHERE F_Id IN (SELECT F_ItemId FROM Base_Authorize WHERE F_ObjectId IN ('{0}') AND F_ItemType = 'module') and F_EnabledMark = '1'  Order by F_SortCode asc", objectId));
                    buttonList = await db.GetListSqlAsync<AuthorizeModuleButtonModel>(string.Format("SELECT * FROM Base_ModuleButton WHERE F_Id IN (SELECT F_ItemId FROM Base_Authorize WHERE F_ObjectId IN ('{0}') AND F_ItemType = 'button') and F_EnabledMark = '1'  Order by F_SortCode asc", objectId));
                    columnList = await db.GetListSqlAsync<AuthorizeModuleColumnModel>(string.Format("SELECT * FROM Base_ModuleColumn WHERE F_Id IN (SELECT F_ItemId FROM Base_Authorize WHERE F_ObjectId IN ('{0}') AND F_ItemType = 'column') and F_EnabledMark = '1'  Order by F_SortCode asc", objectId));
                    resourceList = await db.GetListSqlAsync<AuthorizeModuleResourceModel>(string.Format("SELECT * FROM Base_ModuleDataAuthorizeScheme WHERE F_Id IN (SELECT F_ItemId FROM Base_Authorize WHERE F_ObjectId IN ('{0}') AND F_ItemType = 'resource') and F_EnabledMark = '1'  Order by F_SortCode asc", objectId));
                }
                else
                {
                    moduleList = await db.GetListSqlAsync<AuthorizeModuleModel>(string.Format("SELECT * FROM Base_Module WHERE F_EnabledMark = '{0}' Order by F_SortCode asc", 1));
                    buttonList = await db.GetListSqlAsync<AuthorizeModuleButtonModel>(string.Format("SELECT * FROM Base_ModuleButton WHERE F_EnabledMark = '{0}' Order by F_SortCode asc", 1));
                    columnList = await db.GetListSqlAsync<AuthorizeModuleColumnModel>(string.Format("SELECT * FROM Base_ModuleColumn WHERE F_EnabledMark ='{0}' Order by F_SortCode asc", 1));
                    resourceList = await db.GetListSqlAsync<AuthorizeModuleResourceModel>(string.Format("SELECT * FROM Base_ModuleDataAuthorizeScheme WHERE F_EnabledMark ='{0}' Order by F_SortCode asc", 1));
                }
                return new AuthorizeModel { ModuleList = moduleList, ButtonList = buttonList, ColumnList = columnList, ResourceList = resourceList };
            }
        }
        /// <summary>
        /// 根据用户Id获取列表
        /// </summary>
        /// <param name="applyId">应用Id</param>
        /// <param name="isAdmin">是否管理员</param>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<AuthorizeEntity>> GetListByUserId(bool isAdmin, string userId)
        {
            using (var db = this.Basic)
            {
                if (!isAdmin)
                {
                    var userRelationList = (await db.GetListAsync<UserRelationEntity>(m => m.UserId == userId)).Select(m => m.ObjectId).ToList();
                    userRelationList.Add(userId);
                    var objectId = string.Join("','", userRelationList);
                    return await db.GetListSqlAsync<AuthorizeEntity>("SELECT * FROM Base_Authorize WHERE F_ObjectId IN ('" + objectId + "')");
                }
                else
                {
                    return new List<AuthorizeEntity>();
                }
            }
        }
        /// <summary>
        /// 根据对象Id获取列表
        /// </summary>
        /// <param name="objectId">对象主键</param>
        /// <returns></returns>
        public async Task<List<AuthorizeEntity>> GetListByObjectId(string objectId)
        {
            using (var db = this.Basic)
            {
                var queryWhere = ExtLinq.True<AuthorizeEntity>();
                queryWhere = queryWhere.And(m => m.ObjectId == objectId);
                return await db.GetListAsync<AuthorizeEntity>(queryWhere);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entitys">实体对象</param>
        public async Task Create(List<AuthorizeEntity> entitys)
        {
            using (var db = this.Basic)
            {
                await db.InsertAsync(entitys);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="objectId">对象主键</param>
        /// <param name="entitys">实体对象</param>
        public async Task Create(string objectId, List<AuthorizeEntity> entitys)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.DeleteAsync<AuthorizeEntity>(m => m.ObjectId == objectId && !"portal".Equals(m.ItemType));
                await db.InsertAsync(entitys);
                await db.CommitTransactionAsync();
            }
        }

        /// <summary>
        /// 创建门户权限
        /// </summary>
        /// <param name="itemId">对象主键</param>
        /// <param name="entitys">实体对象</param>
        public async Task CreatePortal(string itemId, List<AuthorizeEntity> entitys)
        {
            using (var db = this.Basic)
            {
                await db.BeginTransactionAsync();
                await db.DeleteAsync<AuthorizeEntity>(m => m.ItemId == itemId);
                await db.InsertAsync(entitys);
                await db.CommitTransactionAsync();
            }
        }

        /// <summary>
        ///门户权限列表
        /// </summary>
        /// <param name="itemId">功能主键</param>
        /// <param name="ObjectType">权限类别（Role）</param>
        public async Task<List<AuthorizeEntity>> GetAuthorizeModelList(string itemId, string ObjectType)
        {
            using (var db = this.Basic)
            {
                return await db.GetListAsync<AuthorizeEntity>(m => m.ItemId == itemId && m.ObjectType == ObjectType);
            }
        }


    }
}
